/*
   Copyright 2012 BiSe Trojanov

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

function rec_up(id){
 if (id_s[id]==1){return;}

 id_t=i_s[id_s[id]-1];

 i_s[id_s[id]]  =id_t;
 i_s[id_s[id_t]]=id;
 id_s[id]--;id_s[id_t]++;

 $('#div'+id).animate({  top: '-='+ms_t,},200,function(){});
 $('#div'+id_t).animate({top: '+='+ms_t,},200,function(){});
 $('#rec'+id)[0].value  =id_s[id];
 $('#rec'+id_t)[0].value=id_s[id_t];
}

function rec_down(id){
 if (id_s[id]==max_i){return;}

 id_t=i_s[id_s[id]+1];

 i_s[id_s[id]]  =id_t;
 i_s[id_s[id_t]]=id;
 id_s[id]++;id_s[id_t]--;

 $('#div'+id).animate({  top: '+='+ms_t,},200,function(){});
 $('#div'+id_t).animate({top: '-='+ms_t,},200,function(){});
 $('#rec'+id)[0].value  =id_s[id];
 $('#rec'+id_t)[0].value=id_s[id_t];
}

function edit(obj){
 window.open(obj.href,'editid'+Math.floor(Math.rand(1000)),'scrollbars=1,resizable=1;location=0');
 return false;
}

// DRAG & DROP
var obj_drag_id =0;
var obj_drag    =false;
var obj_drag_off=10;

function obj_down(obj,event){
 var r =new RegExp('^div([0-9]+)$');
 var r1=obj.id.match(r);
 if (r1==null){return;}
 
 obj_drag_off=0;var ob=obj;
 while (ob!==null){obj_drag_off+=ob.offsetTop;ob=ob.offsetParent;}
 obj_drag_off=event.pageY-obj_drag_off;

 obj_drag_id=r1[1];
 $(obj).css({'z-index':2});
 
 obj_drag   =true;
}

function obj_up(event){
 if (!obj_drag){return;}
 
 var iii=[]; for (var i=1;i<i_s.length;i++){
  iii[i]={
   'id':i_s[i],
   'y' :$('#div'+i_s[i])[0].offsetTop
  }
 }
 for (var i=1;i<i_s.length;i++){
  for (var j=1;j<i_s.length;j++){
   if (iii[i].y<iii[j].y){var t=iii[j];iii[j]=iii[i];iii[i]=t;}
  }
 }
  
 for (var i=1;i<i_s.length;i++){
  i_s[i]=iii[i].id;id_s[iii[i].id]=i;
  $('#rec'+i_s[i])[0].value=i;
  $('#div'+i_s[i]).animate({top: ms_t*(i-1),'z-index':1},200,function(){});
 }
 
 obj_drag=false;
}

function obj_move(obj,event){
 if (!obj_drag){return;}
 
 var new_y=(event.pageY-obj_drag_off);
 if (new_y<-$('#div'+obj_drag_id).height()*3/4){new_y=-Math.round($('#div'+obj_drag_id).height()*3/4);}
 $('#div'+obj_drag_id).css({top: new_y+'px'});
}
